import 'package:dio/dio.dart';
import 'package:lyf_shop/http/core/lyf_error.dart';
import 'package:lyf_shop/http/core/lyf_net_adapter.dart';
import 'package:lyf_shop/http/request/base_request.dart';

/// Dio 适配器
class DioAdapter extends LyfNetAdapter {
  @override
  Future<LyfNetResponse<T>> send<T>(BaseRequest request) async {
    // TODO: implement send
    var response, options = Options(headers: request.header);
    var error;

    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await Dio().get(request.url(), options: options);
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await Dio()
            .post(request.url(), data: request.params, options: options);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response = await Dio()
            .delete(request.url(), data: request.params, options: options);
      }
    } on LyfError catch (e) {
      error = e;
      throw LyfError(e.code ?? -1, e.message ?? '服务开小差了, 别走开');
    }

    return LyfNetResponse(
        data: response.data,
        request: request,
        code: response.code,
        message: response.message);
  }
}
